<template>
	<view class="content">
		<z-paging ref="paging" v-model="filterResult" :auto="false" :use-virtual-list="config.isPaging"
			@query="getSearchList" auto-show-system-loading preload-page="20" :back-to-top-style="{ 'opacity':0.6 }">

			<!-- 顶部导航与搜索 -->
			<template #top>
				<view class="topBox">
					<u-navbar :fixed="false" title="基础树型筛选" :autoBack="true" leftIconColor="#fff">
						<view slot="right">
							<text v-if="config.chooseType != 1" style="color: #fff;"
								@click="confirmMultiSelect">确定</text>
						</view>
					</u-navbar>

					<view class="SearchBox" v-if="config.showSearch">
						<u-search :showAction="true" v-model="config.param[config.SearchKey]" @search="search"
							@custom="search" shape="square" actionText="查询"
							:actionStyle="{ color: '#fff', fontSize: '16px' }" :animation="false" />
					</view>
				</view>

				<!-- 悬浮按钮 -->
				<m-drag-button v-if="config.chooseType != 1" :isDock="true" :existTabBar="true" :initialBottom="160"
					@btnClick="openSelectData">
					<template #BtnContent>
						<text>已选：</text>
						<text>{{ selectedList.length }}</text>
					</template>
				</m-drag-button>

			</template>

			<!-- 左侧树 -->
			<template v-if="config.treeCofig.treePath" #left>
				<scroll-view :scroll-y="false" class="scroll-Y" :style="{ height: scrollHeight + 'px' }"
					style="width: 300rpx;border-right: 1px solid #ebebeb;">
					<m-tree-view :scrollHeight="scrollHeight" @choice="choiceInfo"
						:searchTreeKey="config.treeCofig.treeDisplayValue" :treeData="treeData"
						v-model="selectTreeData" />
				</scroll-view>
			</template>

			<!-- 列表项 -->
			<template #cell="{ item, index }">
				<u-cell :key="index" :title="item[config.keyName]" size="large" @click="innerCellClick(item, index)">
					<template #label>
						<view v-if="config.subText.length">
							<view v-for="row in config.subText" :key="row.labelKey">
								<view v-if="item[row.labelKey]" style="font-size: 14px; color: #999; margin-top: 4px;">
									{{ row.label }} {{ item[row.labelKey] }}
								</view>
							</view>
						</view>
					</template>

					<template #value>
						<checkbox v-if="config.chooseType != 1" :checked="item.checked" class="CheckBox" color="#fff"
							activeBackgroundColor="#51d0d0" activeBorderColor="#51d0d0" />

						<view v-else-if="item.checked">
							<u-icon size="30" name="checkbox-mark" color="#12ce04" />
						</view>
					</template>
				</u-cell>
			</template>
		</z-paging>


		<uni-popup ref="selectPopup" type="bottom" border-radius="10px 10px 0 0">
			<view class="f-dc" style="max-height: 60vh;min-height: 300px;background-color: #fff;"
				:style="$utils.disposeSafeBottomFun()">

				<view style="padding: 8px;border-bottom: 1px solid #f7fcfc;font-size: 12px;font-weight: 600;">
					<text>总数：</text>
					<text>{{selectedList.length}}</text>
				</view>

				<view class="flex-auto">


					<view v-for="(item,index) in selectedList" class="x-bc" hover-class="hoverCell"
						:hover-stay-time="40"
						style="padding: 8px 10px;font-weight: 600;font-size: 14px;border-bottom: 1px solid #f7fcfc;">
						<view class="f-dc">

							<view class="x-f">
								<text>{{index+1}}</text>
								<text style="margin-left: 4px;">{{item[config.keyName]}}</text>
							</view>

							<view v-if="config.subText.length">
								<view v-for="row in config.subText" :key="row.labelKey">
									<view v-if="item[row.labelKey]"
										style="font-size: 12px; color: #999; margin-top: 4px;">
										{{ row.label }} {{ item[row.labelKey] }}
									</view>
								</view>
							</view>
						</view>



						<uni-icons type="closeempty" size="16" style="margin-right: 8px;" color="#f00"
							@click="removeSelected(index)"></uni-icons>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>


<script>
	export default {
		data() {
			return {
				listen: "",
				config: {
					requestType: "$request",
					chooseType: 1, // 1=单选, !=1=多选
					colName: "",
					showSearch: false,
					SearchKey: "SearchKey",
					cmd: "",
					keyName: "",
					keyValue: "",
					ChoiceDataData: null, // ✅ 回显值
					isPaging: false,
					param: {},
					subText: [],
					treeCofig: {
						treeRequestType: "$request",
						treePath: "",
						treeDisplayValue: "",
						treeHiddenValue: "",
						treeParentValues: "",
						treeParams: {}
					}
				},
				treeData: [],
				selectTreeData: null,
				filterResult: [],
				selectedList: [], // ✅ 多选数据池
				scrollHeight: 500
			};
		},
		onLoad(option) {
			if (!this.$utils.isEmpty(option)) {
				this.listen = option.listen;
			}
			const config = this.$utils.deepClone(this.$store.state.BaseScreenParmByTree);
			if (config.showSearch && !config.param.hasOwnProperty(config.SearchKey)) {
				config.param[config.SearchKey] = "";
			}
			Object.assign(this.config, config);

			// 判断是否有选中数据,初始化加载已选中数据
			if (Array.isArray(this.config.ChoiceDataData) && this.config.ChoiceDataData.length) {
				this.fetchSelectedItems(this.config.ChoiceDataData);
			} else {
				this.getTreeData();
			}

			this.scrollHeight = uni.getSystemInfoSync().screenHeight;
			this.getSearchList(1);
		},
		onUnload() {
			this.$store.commit("ChangeAndSetStateData", {
				Name1: "BaseScreenParmByTree",
				data: {}
			});
		},
		methods: {
			// 根据选中 ID 加载完整数据
			fetchSelectedItems(ids) {
				const keyVal = this.config.keyValue;
				// const keyVal = "EquipmentTypeID";
				const requestName = "$promiseRequest";
				const param = {
					...this.config.param,
					[keyVal]: ids.join(',')
				};
				console.log(this.config.cmd);
				console.log(param);
				if (this.config.isPaging) {
					param[this.config.pageIndexStr] = 1;
				}
				// let promiseInfo = this.Request.PromiseRequest(this.config.cmd, param);
				let promiseInfo = this[requestName](this.config.cmd, param);
				console.log(promiseInfo);
				promiseInfo.then(ret => {
					console.log(ret);
				}).catch(err => {
					console.log(err);
				});



				// this.getTreeData();
			},
			getSearchList(pageNo) {
				if (!this.config.cmd) return;
				const param = this.$utils.deepClone(this.config.param);
				const requestName = this.config.requestType || "$request";
				if (this.config.isPaging) {
					param[this.config.pageIndexStr] = pageNo;
				}
				const keyVal = this.config.keyValue;
				const choiceData = this.config.ChoiceDataData;
				const isRadio = this.config.chooseType == 1;

				this[requestName](this.config.cmd, param, (ret) => {
					if (ret.status === 200) {
						const list = ret.data.ds.map(item => {
							const id = item[keyVal];
							let checked = false;
							if (isRadio) {
								checked = id === choiceData;
							} else if (Array.isArray(choiceData)) {
								checked = choiceData.includes(id);
								if (checked && !this.selectedList.some(i => i[keyVal] === id)) {
									this.selectedList.push({
										...item
									});
								}
							}
							return {
								...item,
								checked
							};
						});
						if (this.config.isPaging) {
							this.$refs.paging.complete(list);
						} else {
							this.$refs.paging.setLocalPaging(list);
						}
					} else {
						this.$refs.paging.complete(false);
					}
				}, () => {
					this.$refs.paging.complete(false);
				});
			},
			getTreeData() {
				const config = this.config.treeCofig;
				if (!config.treePath) return;
				const requestName = config.treeRequestType || "$request";
				this[requestName](config.treePath, config.treeParams, (ret) => {
					if (ret.status === 200) {
						const list = ret.data.ds.map(item => ({
							...item,
							label: item[config.treeDisplayValue],
							id: item[config.treeHiddenValue]
						}));
						this.treeData = this.buildTree(list);
					}
				});
			},
			buildTree(data, rootVal = 0) {
				const map = new Map(),
					tree = [];
				for (const item of data) map.set(item.id, {
					...item
				});
				for (const item of data) {
					const node = map.get(item.id);
					const parent = map.get(item.UpID);
					if (item.UpID === rootVal) tree.push(node);
					else if (parent) {
						parent.children = parent.children || [];
						parent.children.push(node);
					}
				}
				return tree;
			},
			search() {
				this.$refs.paging.reload();
			},
			choiceInfo(id) {
				this.config.param[this.config.treeCofig.treeHiddenValue] = id;
				this.search();
			},
			innerCellClick(item, index) {
				const isRadio = this.config.chooseType == 1;
				const keyVal = this.config.keyValue;
				if (isRadio) {
					uni.$emit(this.listen, {
						chooseType: 1,
						colName: this.config.colName,
						data: item,
						index
					});
					uni.navigateBack();
				} else {
					item.checked = !item.checked;
					if (item.checked) {
						const exists = this.selectedList.some(i => i[keyVal] === item[keyVal]);
						if (!exists) this.selectedList.push({
							...item
						});
					} else {
						this.selectedList = this.selectedList.filter(i => i[keyVal] !== item[keyVal]);
					}
				}
			},
			removeSelected(index) {
				const item = this.selectedList[index];
				const keyVal = this.config.keyValue;
				const inList = this.filterResult.find(i => i[keyVal] === item[keyVal]);
				if (inList) inList.checked = false;
				this.selectedList.splice(index, 1);

				if (this.selectedList.length == 0) {
					this.$refs.selectPopup.close();
				}
			},
			openSelectData() {
				if (this.selectedList.length == 0) return;
				// 可打开弹层或新页面展示 selectedList
				this.$refs.selectPopup.open();
			},
			confirmMultiSelect() {

				uni.$emit(this.listen, {
					chooseType: this.config.chooseType,
					colName: this.config.colName,
					data: this.selectedList
				});
				uni.navigateBack();
			}
		}
	}
</script>

<style lang="scss">
	.content {
		.SearchBox {
			background-color: #51d0d0;
			padding: 6px 10px;
		}

		.hoverCell {
			background-color: rgba(235, 0, 12, 0.2);
		}

		.selected-bar {
			padding: 10rpx;
			border-top: 1px solid #eee;
			background-color: #f9f9f9;
		}

		.selected-scroll {
			display: flex;
			flex-direction: row;
		}

		.selected-item {
			display: flex;
			align-items: center;
			background: #e6f7ff;
			border: 1px solid #91d5ff;
			border-radius: 16rpx;
			padding: 0 10rpx;
			margin-right: 10rpx;
			font-size: 12px;

			.text {
				margin-right: 6rpx;
			}
		}
	}
</style>